﻿using B.Z.Inventory.API.Write.Application.Command;
using B.Z.Inventory.ErrorCode;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;

namespace B.Z.Inventory.API.Write.Controllers
{
    /// <summary>
    /// 库存盘点控制器（写）
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class InventoryWriteController : ControllerBase
    {
        private readonly IMediator mediator;

        public InventoryWriteController(IMediator mediator)
        {
            this.mediator = mediator;
        }
        /// <summary>
        /// 库存盘点任务新增
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<int>> AddInventoryTask(InventoryTaskAddCommand request) 
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 给盘点任务单配置盘点的商品
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<int>> AddInventoryGoods(InventoryGoodsAddCommand request) 
        {
            return await mediator.Send(request);
        }
        /// <summary>
        /// 出入库申请单
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<int>> AddintoutStore(IntOutStoreAddCommand request) 
        {
            var result = await mediator.Send(request);
            
            // 如果出入库操作成功，发送SignalR消息通知
            if (result.Code == APIEnums.ok)
            {
                try
                {
                    // 这里需要根据实际情况获取商品名称和操作信息
                    // 由于缺少具体的商品信息，这里提供一个基本的实现框架
                    var messageType = request.IsIntOrOut ? "入库成功" : "出库成功";
                    var operationName = request.IsIntOrOut ? "入库" : "出库";
                    
                    // 注意：这里需要根据实际的项目结构来实现SignalR通知
                    // 可能需要通过HTTP请求调用读取API的SignalR方法，或者通过共享服务来实现
                }
                catch (Exception ex)
                {
                    // SignalR通知失败不应该影响业务操作的结果
                    // 记录日志即可
                }
            }
            
            return result;
        }
    }
}
